import { useMemoizedFn } from 'ahooks'
import { ArrowDownAZ, ArrowUpZA, PlusIcon, Trash2, Zap } from 'lucide-react'
import React, { useState } from 'react'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useAutoPopUpActions, useCurrentAutoPopUp } from '@/hooks/useAutoPopUp'
import { useToast } from '@/hooks/useToast'
import GoodsListItem from './GoodsListItem'
import ShortcutConfigTab from './ShortcutConfigTab'

const CommonList = () => {
  const goodsIds = useCurrentAutoPopUp(context => context.config.goodsIds)
  const { setGoodsIds } = useAutoPopUpActions()
  const { toast } = useToast()
  const [batchDialogOpen, setBatchDialogOpen] = useState(false)
  const [batchInput, setBatchInput] = useState('')
  const [clearDialogOpen, setClearDialogOpen] = useState(false)
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc') // 排序方向：asc=正序，desc=倒序

  const handleGoodsIdChange = useMemoizedFn((index: number, value: string) => {
    const numValue = Number(value)
    if (Number.isNaN(numValue) || numValue < 1) {
      toast.error('请输入有效的商品序号')
      return
    }
    const newIds = [...goodsIds]
    if (newIds.includes(numValue)) {
      toast.error('商品序号不能重复！')
      return
    }
    newIds[index] = numValue

    setGoodsIds(newIds)
  })

  const addGoodsId = useMemoizedFn(() => {
    if (goodsIds.length >= 200) {
      toast.error('商品列表最多只能添加200个商品')
      return
    }
    let id = 1
    while (goodsIds.includes(id)) id += 1
    setGoodsIds([...goodsIds, id])
  })

  // 排序功能 - 支持正序和倒序切换
  const sortGoodsIds = useMemoizedFn(() => {
    const newOrder = sortOrder === 'asc' ? 'desc' : 'asc'
    const sorted = [...goodsIds].sort((a, b) => {
      return newOrder === 'asc' ? a - b : b - a
    })
    setGoodsIds(sorted)
    setSortOrder(newOrder)
    toast.success(newOrder === 'asc' ? '已按正序排序' : '已按倒序排序')
  })

  // 清空全部功能
  const clearAllGoods = useMemoizedFn(() => {
    setGoodsIds([])
    setClearDialogOpen(false)
    toast.success('已清空所有商品')
  })

  // 批量生成功能
  const batchGenerate = useMemoizedFn(() => {
    const input = batchInput.trim()
    
    // 支持格式: "1-20" 或 "1,2,3,4,5"
    let newIds: number[] = []
    
    if (input.includes('-')) {
      // 范围格式: "1-20"
      const [start, end] = input.split('-').map(s => Number(s.trim()))
      
      if (Number.isNaN(start) || Number.isNaN(end) || start < 1 || end < 1) {
        toast.error('请输入有效的范围，例如: 1-20')
        return
      }
      
      if (start > end) {
        toast.error('起始值不能大于结束值')
        return
      }
      
      if (end - start > 199) {
        toast.error('一次最多生成200个商品')
        return
      }
      
      for (let i = start; i <= end; i++) {
        newIds.push(i)
      }
    } else if (input.includes(',')) {
      // 逗号分隔格式: "1,2,3,4,5"
      newIds = input.split(',').map(s => Number(s.trim())).filter(n => !Number.isNaN(n) && n >= 1)
      
      if (newIds.length === 0) {
        toast.error('请输入有效的商品序号')
        return
      }
      
      if (newIds.length > 200) {
        toast.error('一次最多生成200个商品')
        return
      }
    } else {
      toast.error('请使用正确的格式，例如: 1-20 或 1,2,3,4,5')
      return
    }
    
    // 合并现有的和新生成的，去重
    const combined = [...goodsIds, ...newIds]
    const unique = Array.from(new Set(combined)).sort((a, b) => a - b)
    
    // 检查总数是否超过200
    if (unique.length > 200) {
      toast.error(`商品列表最多只能有200个，当前尝试添加后将有 ${unique.length} 个商品`)
      return
    }
    
    setGoodsIds(unique)
    setBatchDialogOpen(false)
    setBatchInput('')
    toast.success(`成功生成 ${newIds.length} 个商品`)
  })
  return (
    <>
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div className="space-y-1">
            <Label>商品列表</Label>
            <p className="text-sm text-muted-foreground">
              添加需要自动弹出的商品序号
            </p>
            <p className="text-xs text-green-600">
              ✓ 如果某个商品不存在，系统会自动跳过换下一个商品
            </p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={addGoodsId}>
              <PlusIcon className="mr-2 h-4 w-4" />
              添加商品
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setBatchDialogOpen(true)}
            >
              <Zap className="mr-2 h-4 w-4" />
              批量生成
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={sortGoodsIds}
              disabled={goodsIds.length === 0}
              title={sortOrder === 'asc' ? '点击倒序排序' : '点击正序排序'}
            >
              {sortOrder === 'asc' ? (
                <>
                  <ArrowDownAZ className="mr-2 h-4 w-4" />
                  正序
                </>
              ) : (
                <>
                  <ArrowUpZA className="mr-2 h-4 w-4" />
                  倒序
                </>
              )}
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setClearDialogOpen(true)}
              disabled={goodsIds.length === 0}
            >
              <Trash2 className="mr-2 h-4 w-4" />
              清空全部
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-6 gap-4">
          {goodsIds.map((id, index) => (
            <GoodsListItem
              // biome-ignore lint/suspicious/noArrayIndexKey: 下标不影响
              key={index}
              id={id}
              index={index}
              onChange={handleGoodsIdChange}
              onDelete={() => {
                const newGoodsIds = goodsIds.filter((_, i) => i !== index)
                setGoodsIds(newGoodsIds)
              }}
            />
          ))}
        </div>
      </div>

      {/* 批量生成对话框 */}
      <Dialog open={batchDialogOpen} onOpenChange={setBatchDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>批量生成商品</DialogTitle>
            <DialogDescription>
              输入商品序号范围或列表，支持两种格式：
              <br />
              • 范围格式：1-20（生成1到20的商品）
              <br />
              • 列表格式：1,2,3,4,5（生成指定的商品）
              <br />
              <span className="text-amber-600">⚠️ 注意：一次最多生成200个商品，商品列表最多200个</span>
              <br />
              <span className="text-green-600">✓ 如果某个商品不存在，系统会自动跳过换下一个</span>
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="batch-input">商品序号</Label>
              <Input
                id="batch-input"
                placeholder="例如: 1-20 或 1,2,3,4,5"
                value={batchInput}
                onChange={e => setBatchInput(e.target.value)}
                onKeyDown={e => {
                  if (e.key === 'Enter') {
                    batchGenerate()
                  }
                }}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setBatchDialogOpen(false)
                setBatchInput('')
              }}
            >
              取消
            </Button>
            <Button onClick={batchGenerate}>生成</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 清空确认对话框 */}
      <AlertDialog open={clearDialogOpen} onOpenChange={setClearDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认清空</AlertDialogTitle>
            <AlertDialogDescription>
              确定要清空所有商品吗？此操作不可恢复。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={clearAllGoods}>确认清空</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

// 商品列表卡片组件
const GoodsListCard = React.memo(() => {
  return (
    <Card>
      <CardContent className="pt-6">
        <Tabs defaultValue="goods-list" className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="goods-list">商品列表</TabsTrigger>
            <TabsTrigger value="shortcuts">快捷键配置</TabsTrigger>
          </TabsList>

          <TabsContent value="goods-list" className="space-y-6 mt-4">
            <CommonList />
          </TabsContent>

          <TabsContent value="shortcuts" className="mt-4">
            <ShortcutConfigTab />
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  )
})

export default GoodsListCard
